package pub.guoxin.oops.msg;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import pub.guoxin.oops.utils.JsonUtils;

/**
 * 消息生产者
 */
@Slf4j
@Component
public class MessageDataProducer {

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * convert json sender
     *
     * @param topicName
     * @param objectMessage
     */
    public void sender(String topicName, Object objectMessage) {
        String json = JsonUtils.obj2json(objectMessage);
        log.info("sending topicName: '{}' to length: '{}'", topicName, json.length() / 2);
        try {
            kafkaTemplate.send(topicName, json);
        } catch (Exception e) {
            log.error("发送数据出错！！！{}{}", topicName, json);
            log.error("发送数据出错=====>", e);
        }
    }

    /**
     * sender
     *
     * @param topicName
     * @param stringMessage
     */
    public void sender(String topicName, String stringMessage) {
        log.info("sending topicName: '{}' to length: '{}'", topicName, stringMessage.length() / 2);
        try {
            kafkaTemplate.send(topicName, stringMessage);
        } catch (Exception e) {
            log.error("发送数据出错！！！{}{}", topicName, stringMessage);
            log.error("发送数据出错=====>", e);
        }
    }

}
